package com.hjy.cabinet.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.hjy.cabinet.db.domain.BaseConfig;

import java.util.ArrayList;
import java.util.List;

public class BaseConfigHelper extends SQLiteOpenHelper {

    // 数据库名称
    private static final String DATABASE_NAME = "BaseConfig.db";
    // 数据库版本
    private static final int DATABASE_VERSION = 100;
    // 表名
    private static final String TABLE_NAME = "config";
    // 字段名
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_VALUE = "value";

    // 创建表的SQL语句
    private static final String CREATE_TABLE_SQL =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_NAME + " TEXT UNIQUE, " +  // 添加UNIQUE约束
                    COLUMN_VALUE + " TEXT" +
                    ")";

    public BaseConfigHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建表
        db.execSQL(CREATE_TABLE_SQL);
        // 插入默认数据
        insertDefaultConfigs(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 删除旧表并重新创建
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        onCreate(db);
    }

    /**
     * 插入默认配置项
     *
     * @param db SQLiteDatabase 对象
     */
    private void insertDefaultConfigs(SQLiteDatabase db) {
        String[] names = {
                "editTemperatureUp",
                "editTemperatureDown",
                "tempoliceTime",
                "editHumidityUp",
                "editHumidityDown",
                "humPoliceTime",
                "ip",
                "noOperationBackTime",
                "doorNoCloseTime"
        };

        for (String name : names) {
            ContentValues values = new ContentValues();
            values.put(COLUMN_VALUE, "0"); // 默认值为 0
            if("ip".equals(name)){
                values.put(COLUMN_VALUE, "192.168.1.168"); // 默认值为 0
            }

            values.put(COLUMN_NAME, name);
            db.insert(TABLE_NAME, null, values);
        }
    }


    /**
     * 添加配置项
     *
     * @param name  配置项名称
     * @param value 配置项值
     * @return 返回插入的行数
     */
    public long addConfig(String name, String value) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, name);
        values.put(COLUMN_VALUE, value);
        long result = db.insert(TABLE_NAME, null, values);
        db.close();
        return result;
    }

    /**
     * 更新配置项
     *
     * @param id    配置项ID
     * @param name  配置项名称
     * @param value 配置项值
     * @return 返回更新的行数
     */
    public int updateConfig(long id, String name, String value) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, name);
        values.put(COLUMN_VALUE, value);
        int result = db.update(TABLE_NAME, values, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
        return result;
    }

    /**
     * 删除配置项
     *
     * @param id 配置项ID
     * @return 返回删除的行数
     */
    public int deleteConfig(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        int result = db.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
        return result;
    }

    /**
     * 获取配置项
     *
     * @param id 配置项ID
     * @return 返回配置项的Cursor
     */
    public BaseConfig getConfig(long id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_ID, COLUMN_NAME, COLUMN_VALUE}, COLUMN_ID + " = ?", new String[]{String.valueOf(id)}, null, null, null);
        BaseConfig baseConfig = dealCursorData(cursor);
        return baseConfig;
    }


    /**
     * 获取配置项根据姓名
     *
     * @param name 配置项name
     * @return 返回配置项的Cursor
     */
    public BaseConfig getConfigByName(String name) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_ID, COLUMN_NAME, COLUMN_VALUE}, COLUMN_NAME + " = ?", new String[]{name}, null, null, null);
        BaseConfig baseConfig = dealCursorData(cursor);
        return baseConfig;
    }

    /**
     * 获取所有配置
     *
     * @return List<BaseConfig>
     */
    public List<BaseConfig> getAllConfigs() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        List<BaseConfig> configList = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                BaseConfig config = new BaseConfig();
                config.setId(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_ID)));
                config.setName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME)));
                config.setValue(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_VALUE)));
                configList.add(config);
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }
        return configList;
    }


    public BaseConfig dealCursorData(Cursor cursor){

        BaseConfig config = null;
        if (cursor != null && cursor.moveToFirst()) {
            config = new BaseConfig();
            config.setId(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_ID)));
            config.setName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME)));
            config.setValue(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_VALUE)));
        }

        if (cursor != null) {
            cursor.close();
        }

        return config;
    }


}